<template>
	<view>
		
		<view class="login">
			<view class="content">
				
				<h1 class="title">中式简餐供应链平台</h1>
				
				<!-- 头部logo -->
				<view class="header">
					<image class="header" src="./logo.png"></image>
				</view>
				
				<!-- 手机号登录主体 2-->
				<view class="main">
					<wInput v-model="phoneData" type="text" maxlength="40" autocomplete="off" placeholder="请输入11位注册手机号"></wInput>
					<wInput v-model="passData" type="password" maxlength="32" placeholder="请输入密码" isShowPass ref="runCode"
					 autocomplete="off" @setCode="getVerCode()"></wInput>
				</view>
				<wButton text="登 录 系 统" :rotate="isRotate" @click.native="startLoginPhone()"></wButton>


				<!-- 其他登录 -->
				<!--  #ifdef APP-PLUS -->
				<view class="other_login cuIcon">

					<!-- <view class="login_icon">
						<view class="cuIcon-weixin" @tap="login_weixin"></view>
					</view> -->

				</view>
				<!--  #endif -->
				<!--  #ifdef H5 -->

				<!--  #endif -->

				<!-- 底部信息 -->
				<view class="footer">
					<navigator url="/apiPam/register/main" open-type="navigate">还没有账号？点这里注册吧</navigator>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		logincommonAccountApi,
		memberInfoApi
	} from "@/server/config.js";
	import {
		quit,
		getStorageUserInfo,
		redirectURL,
		appid
	} from "@/server/api.js";
	import wInput from "@/components/watch-login/watch-input.vue"; //input
	import wButton from "@/components/watch-login/watch-button.vue"; //button

	export default {
		onLoad(options) {
			this.logo();
			this.code = options.code;
			// this.code = "0812k87719EI7O1ZsD471TYb7712k87x";
			if (this.code) {
				uni.setStorageSync("code", this.code)
				this.getuserinfo();
			}
		},
		data() {
			return {
				isWeixin: false,
				// logoImage:"https://imgt1.oss-cn-shanghai.aliyuncs.com/ecAllRes/images/logo.png",
				logoImage: "",
				phoneData: "", //用户/电话
				reg: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
				mailData: "test@163.com", //用户/邮箱
				passData: "", //密码
				isRotate: false, //是否加载旋转
				userInfo: [],
				accesstoken: "",
				verCode: "",
				typeaClass: "",
				typebClass: "hide",
				code: "", //微信回调的code
				nickname: ""
			};
		},
		components: {
			wInput,
			wButton
		},
		mounted() {
			let ua = navigator.userAgent.toLowerCase();
			//如果是微信浏览器就显示微信登楼
			if (ua.search(/micromessenger/i) > -1) {
				this.isWeixin = true;
			} else {
				this.isWeixin = false;
			}
		},
		methods: {
			async logo() {
				//const data = await loginLogo({});
				this.logoImage = '/yoush/static/images/ysh.jpeg';
			},
			async getVerCode() {
				//获取验证码
				// if (this.phoneData.length != 11) {
				//   uni.showToast({
				//     icon: "none",
				//     position: "bottom",
				//     title: "手机号不正确"
				//   });
				//   return false;
				// }
				if (!this.reg.test(this.mailData)) {
					uni.showToast({
						icon: "none",
						position: "bottom",
						title: "邮箱格式不正确"
					});
					return false;
				}
				const data = await emailPwdSendSmsApi({
					mail: this.mailData,
					user_name: '用户',
					title: '用户登录',
				});
				if (data.data.res === false) {
					//模拟倒计时触发
					uni.showToast({
						icon: "none",
						position: "bottom",
						title: "该邮箱不存在"
					});
					return false;
				}
				if (data.data.res === true) {
					//模拟倒计时触发
					this.$refs.runCode.$emit("runCode"); //触发倒计时（一般用于请求成功验证码后调用）
					uni.showToast({
						icon: "none",
						position: "bottom",
						title: "获取验证码成功"
					});
				}

				// setTimeout(function() {
				//   this.$refs.runCode.$emit("runCode", 0); //假装模拟下需要 终止倒计时
				//   uni.showToast({
				//     icon: "none",
				//     position: "bottom",
				//     title: "模拟倒计时终止"
				//   });
				// }, 3000);
			},
			switchType(type) {
				if (type === "showa") {
					this.typeaClass = "hide";
					this.typebClass = "";
				}
				if (type === "showb") {
					this.typebClass = "hide";
					this.typeaClass = "";
				}

				console.log(type);
			},
			async startLoginAccount() {
				//登录
				if (this.isRotate) {
					//判断是否加载中，避免重复点击请求
					return false;
				}
				// if (this.phoneData.length == "") {
				//   uni.showToast({
				//     icon: "none",
				//     position: "bottom",
				//     title: "用户名不能为空"
				//   });
				//   return;
				// }
				if (this.mailData.length == "") {
					uni.showToast({
						icon: "none",
						position: "bottom",
						title: "用户名不能为空"
					});
					return;
				}
				if (this.passData.length < 5) {
					uni.showToast({
						icon: "none",
						position: "bottom",
						title: "密码不正确"
					});
					return;
				}


				// uni.clearStorageSync();
				quit();

				this.accesstoken = 'test';
				this.user_id = 1;

				this.userInfo = {
					// nickName: this.phoneData,
					nickName: '小同学',
					language: "zh_CN",
					avatarUrl: "https://imgt1.oss-cn-shanghai.aliyuncs.com/ecAllRes/images/missing-face.png"
				};

				uni.setStorageSync("userInfo", this.userInfo);
				uni.setStorageSync("accesstoken", this.accesstoken);
				uni.setStorageSync("user_id", this.user_id);
				// #ifdef MP-WEIXIN
				uni.setStorageSync("tagtype", "weixin");
				// #endif
				// #ifdef MP-ALIPAY
				uni.setStorageSync("tagtype", "alipay");
				// #endif
				// #ifdef H5
				uni.setStorageSync("tagtype", "general");
				// #endif
				console.log("登录成功");

				uni.switchTab({
					url: "/pages/my/main"
				});
				// this.isRotate=true
				// setTimeout(function(){
				// 	this.isRotate=false
				// },3000)
			},
			async startLoginPhone() {
				//登录
				if (this.isRotate) {
					//判断是否加载中，避免重复点击请求
					return false;
				}
				if (this.phoneData.length != 11) {
					uni.showToast({
						icon: "none",
						position: "bottom",
						title: "手机号不正确"
					});
					return false;
				}

				//登录

				const {
					data,
					statusCode
				} = await logincommonAccountApi({
					username: this.phoneData,
					password: this.passData
				});

				if (statusCode == 401) {
					let errors = data.errors;
					let msg = []
					if (errors.length > 0) {
						errors.forEach(p => {
							msg.push(p.message)
						})
					}

					uni.showToast({
						title: msg.join('\r\n'), //提示的内容,
						duration: 2000, //延迟时间,
						icon: "none",
						mask: true, //显示透明蒙层，防止触摸穿透,
						success: res => {}
					});
					return false;
				}

				//登录成功
				if (statusCode == 200) {
					uni.setStorageSync("accesstoken", data.access_token);
				} else {
					uni.showToast({
						title: "登录失败，请重新登录", //提示的内容,
						duration: 3000, //延迟时间,
						icon: "none",
						mask: true, //显示透明蒙层，防止触摸穿透,
						success: res => {}
					});
					return
				}

				//获取会员信息
				//保存会员信息
				const res = await memberInfoApi();
				if (res.statusCode == 200) {
					uni.setStorageSync("userInfo", res.data);
					console.log('登录成功')
					//页面导航
					if(this.isWeixin) {// 判断是否在服务号打开，并授权服务号登录
						console.log('weixin')
						const url = encodeURIComponent(redirectURL)
						const authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+url+"&response_type=code&scope=snsapi_base&state=12345#wechat_redirect"
						console.log(authUrl)
						// 登录成功之后进行服务号授权
						location.href = authUrl
					} else {
						console.log('not weixin')
						uni.switchTab({
							url: "/pages/index/main"
						});
					}
				}

			},
			async login_weixin() {
				//H5-APP微信登录开始
				uni.getProvider({
					service: "oauth",
					// provider: 'weixin',
					success: function(res) {
						console.log("微信登录");
						console.log(res.provider);
						if (~res.provider.indexOf("weixin")) {
							uni.login({
								provider: "weixin",
								success: async function(loginRes) {
									// 登录成功 将数据存入缓存

									uni.setStorageSync("openId", loginRes.authResult.openid);
									uni.setStorageSync(
										"access_token",
										loginRes.authResult.access_token
									); // 获得用户的头像等信息需要改参数  时效时间两小时左右
									// 检测微信是否注册过了  同时返回用户的头像及昵称
									const data = await checkWechatRegApi({
										openid: loginRes.authResult.openid,
										access_token: loginRes.authResult.access_token
									});

									if (data.data.res === false) {
										// 尚未注册
										uni.navigateTo({
											url: "/apiPam/binding/main"
										});
										return false;
									}
									/**
									 * data.data.avatar_url 为返回的用户头像 暂时使用默认的
									 */
									// uni.clearStorageSync();
									quit();

									uni.setStorageSync("userInfo", {
										nickName: data.data.nickname,
										language: "zh_CN",
										avatarUrl: data.data.avatar_url
									});

									uni.setStorageSync("userInfo", {
										nickName: data.data.nickname,
										language: "zh_CN",
										avatarUrl: data.data.avatar_url
									});
									uni.setStorageSync("accesstoken", data.data.sess_id);
									uni.setStorageSync("user_id", data.data.user_id);
									// #ifdef MP-WEIXIN
									uni.setStorageSync("tagtype", "weixin");
									// #endif
									// #ifdef MP-ALIPAY
									uni.setStorageSync("tagtype", "alipay");
									// #endif
									// #ifdef H5
									uni.setStorageSync("tagtype", "general");
									// #endif

									console.log("登录成功");
									uni.switchTab({
										url: "/pages/my/main"
									});
								}
							});
						}
					}
				});
			},
			login_global() {
				//H5-APP支付宝登录开始
			},
			async login_weixin_H5() {
				const data = await getWxAuthApi({});
				window.location.href = data.data.url;



			},
			async getuserinfo() {
				const information = await getWXUserInfoApi({
					code: this.code
				});

				// console.log(information)
				// console.log('111111111')
				// console.log(information.data.nickname)
				quit();



				uni.setStorageSync("userInfo", {
					nickName: information.data.nickname,
					language: "zh_CN",
					avatarUrl: information.data.avatar_url
				});



				uni.setStorageSync("accesstoken", information.data.sess_id);
				uni.setStorageSync("user_id", information.data.user_id);
				uni.setStorageSync("openid", information.data.openid);

				// #ifdef H5
				uni.setStorageSync("tagtype", "general");
				// #endif


				console.log("登录成功123");
				uni.switchTab({
					url: "/pages/my/main"
				});
			}

		}
	};
</script>

<style lang='scss' scoped>
	@import url("../../components/watch-login/css/icon.css");
	@import "./style";
</style>
